package discover

import (
	"context"
	"time"

	"github.com/lukeaxu/discover/registry"
	"google.golang.org/grpc/resolver"
)

type grpcResolver struct {
	cc       resolver.ClientConn
	registry registry.Registry
	target   resolver.Target
	timeout  time.Duration // 解析的最大延迟
	close    chan struct{}
}

func (g *grpcResolver) ResolveNow(resolver.ResolveNowOptions) {
	g.resolveNow()
}

func (g *grpcResolver) resolveNow() {
	ctx, cancel := context.WithTimeout(context.Background(), g.timeout)
	defer cancel()
	services, err := g.registry.ListServices(ctx, g.target.Endpoint())
	if err != nil {
		g.cc.ReportError(err)
		return
	}
	addresses := make([]resolver.Address, len(services))
	for i, service := range services {
		addresses[i] = resolver.Address{
			Addr: service.Addr,
		}
	}
	err = g.cc.UpdateState(resolver.State{Addresses: addresses})
	if err != nil {
		g.cc.ReportError(err)
		return
	}
}

func (g *grpcResolver) Close() {
	close(g.close)
}
